package com.kanbox.api;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.InputStreamEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.kanbox.api.KanboxServer.KanboxHttp;

public class Kanbox {

    public static boolean TEST = false;
    /**
     *
     */
    public static void getOauth(Context context, String client_id,
            String client_secret, String redirect_uri) {
        String getCodeUrl = "https://auth.kanbox.com/0/auth?response_type=code&client_id="
                + client_id
                + "&platform=android"
                + "&redirect_uri="
                + redirect_uri + "&user_language=ZH";
        if(TEST){
            getCodeUrl = "http://auth.kanbox.com/0/auth?response_type=code&client_id="
                    + client_id
                    + "&platform=android"
                    + "&redirect_uri="
                    + redirect_uri + "&user_language=ZH";
        }
        Intent sIntent = new Intent(context, Oauth.class);
        sIntent.putExtra("url", getCodeUrl);
        sIntent.putExtra("client_id", client_id);
        sIntent.putExtra("client_secret", client_secret);
        sIntent.putExtra("redirect_uri", redirect_uri);
        context.startActivity(sIntent);
    }

    /**
     *
     *
     * @param listener
     */
    public static void getAccountInfo(RequestListener listener) {
        String getAccountInfoUrl = "https://api.kanbox.com/0/info";
        if(TEST){
            getAccountInfoUrl = "http://api.kanbox.com/0/info";
        }
        HttpRequestBase httpMethod = KanboxHttp.doGet(getAccountInfoUrl,
                Token.getInstance());
        KanboxServer.getInstance().doHttp(httpMethod, listener,
                Constant.OP_GET_ACCCOUNT_INFO);
    }

    /**
     *
     *
     * @param path
     *
     * @param listener
     */
    public static void getFileList(String path, RequestListener listener) {
        String getFileListUrl = "https://api.kanbox.com/0/list";
        if(TEST){
             getFileListUrl = "http://api.kanbox.com/0/list";
        }

        if(!TextUtils.isEmpty(path)){
            path = URLEncoder.encode(path);
        }
        HttpRequestBase httpMethod = KanboxHttp.doGet(getFileListUrl + path,
                Token.getInstance());
        KanboxServer.getInstance().doHttp(httpMethod, listener, Constant.OP_GET_FILELIST);
    }

    /**
     *
     *
     * @param sourcePath
     *
     * @param desPath
     *
     * @param listener
     */
    public static void moveFile(String sourcePath, String desPath,
            RequestListener listener) {
        String moveUrl = "https://api.kanbox.com/0/move";
         if(TEST){
             moveUrl = "http://api.kanbox.com/0/move";
        }
         if(!TextUtils.isEmpty(sourcePath)){
             sourcePath = URLEncoder.encode(sourcePath);
         }
         if(!TextUtils.isEmpty(desPath)){
             desPath = URLEncoder.encode(desPath);
         }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("path", sourcePath);
        params.put("destination_path", desPath);

        HttpRequestBase httpMethod = KanboxHttp.doGet(moveUrl, params,
                Token.getInstance());
        KanboxServer.getInstance().doHttp(httpMethod, listener, Constant.OP_MOVE);
    }

    /**
     *
     *
     * @param sourcePath
     *
     * @param desPath
     *
     * @param listener
     */
    public static void copyFile(String sourcePath, String desPath,
            RequestListener listener) {
        String moveUrl = "https://api.kanbox.com/0/copy";
        if(TEST){
            moveUrl = "http://api.kanbox.com/0/copy";
       }
        if(!TextUtils.isEmpty(sourcePath)){
            sourcePath = URLEncoder.encode(sourcePath);
        }
        if(!TextUtils.isEmpty(desPath)){
            desPath = URLEncoder.encode(desPath);
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("path", sourcePath);
        params.put("destination_path", desPath);

        HttpRequestBase httpMethod = KanboxHttp.doGet(moveUrl, params,
                Token.getInstance());
        KanboxServer.getInstance().doHttp(httpMethod, listener, Constant.OP_COPY);
    }

    /**
     *
     *
     * @param path
     *
     * @param listener
     */
    public static void deleteFile(String path, RequestListener listener) {
        String moveUrl = "https://api.kanbox.com/0/delete";
        if(TEST){
            moveUrl = "http://api.kanbox.com/0/delete";
       }
        if(!TextUtils.isEmpty(path)){
            path = URLEncoder.encode(path);
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("path", path);

        HttpRequestBase httpMethod = KanboxHttp.doGet(moveUrl, params,
                Token.getInstance());
        KanboxServer.getInstance().doHttp(httpMethod, listener, Constant.OP_DELETE);
    }

    /**
     *
     *
     * @param path
     *
     * @param listener
     */
    public static void makeDir(String path, RequestListener listener) {
        String moveUrl = "https://api.kanbox.com/0/create_folder";
        if(TEST){
            moveUrl = "http://api.kanbox.com/0/create_folder";
       }
        if(!TextUtils.isEmpty(path)){
            path = URLEncoder.encode(path);
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("path", path);

        HttpRequestBase httpMethod = KanboxHttp.doGet(moveUrl, params,
                Token.getInstance());
        KanboxServer.getInstance().doHttp(httpMethod, listener, Constant.OP_MAKE_DIR);

    }

    /**
     *
     *
     * @param emails
     *
     * @param path
     *
     * @param listener
     * @throws UnsupportedEncodingException
     */
    public static void makeShareDir(ArrayList<String> emails, String path,
            RequestListener listener) throws UnsupportedEncodingException {
        String makeShareDirUrl = "https://api.kanbox.com/0/share";
        JSONArray params = new JSONArray();
        for (String string : emails) {
            params.put(string);
        }

        HttpRequestBase httpMethod = KanboxHttp.doPost(makeShareDirUrl + path,
                params.toString(), Token.getInstance());
        KanboxServer.getInstance().doHttp( httpMethod, listener,
                Constant.OP_MAKE_SHARE_DIR);
    }

    /**
     *
     *
     * @param listener
     */
    public static void getShareInviteList(RequestListener listener) {
        String getShareInviteUrl = "https://api.kanbox.com/0/pendingshares";
        HttpRequestBase httpMethod = KanboxHttp.doGet(getShareInviteUrl,
                Token.getInstance());
        KanboxServer.getInstance().doHttp(httpMethod, listener,
                Constant.OP_GET_SHARE_INVITE_LIST);
    }

    /**
     *
     *
     * @param shareDir
     *
     * @param inviter
     *
     * @param accept
     *
     * @param listener
     * @throws JSONException
     * @throws UnsupportedEncodingException
     */
    public static void handleShareInvite(String shareDir, String inviter,
            boolean accept, RequestListener listener) throws JSONException,
            UnsupportedEncodingException {
        String handleShareInviteUrl = "https://api.kanbox.com/0/pendingshares";
        JSONObject params = new JSONObject();
        params.put("path", shareDir);
        params.put("user", inviter);
        params.put("accept", accept);
        String strParams = params.toString();
        // strParams.replaceAll("\\\\/", "/");
        Log.e("test", strParams);
        HttpRequestBase httpMethod = KanboxHttp.doPost(handleShareInviteUrl,
                strParams, Token.getInstance());
        KanboxServer.getInstance().doHttp(httpMethod, listener,
                Constant.OP_HANDLE_SHARE_INVITE);
    }

    /**
     *
     *
     * @param path
     *
     * @param listene
     */
    public static void checkSharedOwner(String path, RequestListener listener) {
        String url = "https://api.kanbox.com/0/checkowner";
        HttpRequestBase httpMethod = KanboxHttp.doGet(url + path,
                Token.getInstance());
        KanboxServer.getInstance().doHttp(httpMethod, listener,
                Constant.OP_SHARED_BY_SELF);
    }

    /**
     *
     *
     * @param Path
     *
     * @param destPath
     *
     * @param listener
     */
    public static void download(String path, String destPath,
            DownloadFileStatus listener) {
        String downloadUrl = "https://api.kanbox.com/0/download";
        if(TEST){
             downloadUrl = "http://api.kanbox.com/0/download";
        }
        if(!TextUtils.isEmpty(path)){
            path = URLEncoder.encode(path);
        }
        HttpRequestBase httpMethod = KanboxHttp.doGet(downloadUrl + path,
                Token.getInstance());
        KanboxServer.getInstance().download(destPath, httpMethod, listener, Constant.OP_DOWNLOAD);
    }
       /**
     *
     *
     * @param src
     *
     * @param listener
     */
    public static void getThumbnail(String src,String destPath,String size, DownloadFileStatus listener) {
        String getFileListUrl = "https://api.kanbox.com/0/thumbnail";
        if(TEST){
             getFileListUrl = "http://api.kanbox.com/0/thumbnail";
        }
        if(!TextUtils.isEmpty(src)){
            src = URLEncoder.encode(src);
        }
        getFileListUrl = getFileListUrl + src+"?size="+size;
        Log.e("FileListFragment","getThumbnail url is "+getFileListUrl);

        HttpRequestBase httpMethod = KanboxHttp.doGet(getFileListUrl,
                Token.getInstance());
        KanboxServer.getInstance().download(destPath,httpMethod, listener, Constant.OP_GET_THUMBNAIL);
    }

    /**
     *
     *
     * @param localPath
     *
     * @param destPath
     *
     * @param listener
     * @throws IOException
     */
    public static void upload(String localPath, String destPath,
            UploadFileStatus listener) throws IOException {
        String uploadUrl = "https://api-upload.kanbox.com/0/upload";
        if(TEST){
            uploadUrl = "http://api-upload.kanbox.com/0/upload";
        }
        HttpPost httpMethod = KanboxHttp.doPost(uploadUrl + destPath, null,
                Token.getInstance());
        listener.onStart(Constant.OP_UPLOAD);
        InputStream is = new MyFileInputStream(localPath, listener);
        httpMethod.setEntity(new InputStreamEntity(is, is.available()));
        KanboxServer.getInstance().upload(destPath, httpMethod, listener, Constant.OP_UPLOAD);
    }

    /**
     *
     *
     * @param is
     *
     * @param destPath
     *
     * @param listener
     * @throws IOException
     */
    public static void uploadInputStream(InputStream is, String destPath,
            UploadFileStatus listener) throws IOException {
        String uploadUrl = "https://api-upload.kanbox.com/0/upload";
        if(TEST){
            uploadUrl = "http://api-upload.kanbox.com/0/upload";
        }
        HttpPost httpMethod = KanboxHttp.doPost(uploadUrl + destPath, null,
                Token.getInstance());
        listener.onStart(Constant.OP_UPLOAD);
        httpMethod.setEntity(new InputStreamEntity(is, is.available()));
        KanboxServer.getInstance().upload(destPath, httpMethod, listener, Constant.OP_UPLOAD);
    }

    public static void disconnectKanbox(){
        KanboxServer.getInstance().disconnectKanboxService();
    }

    protected static class MyFileInputStream extends FileInputStream {
        private UploadFileStatus listener;
        private int offset;
        private long lastListened = 0;
        private long intervalMs = 500;

        public MyFileInputStream(String path, UploadFileStatus listener)
                throws FileNotFoundException {
            super(path);
            this.listener = listener;
            offset = 0;

        }

        @Override
        public int read(byte[] buffer, int byteOffset, int byteCount)
                throws IOException {
            int res = super.read(buffer, byteOffset, byteCount);
            offset += byteCount;

            long now = System.currentTimeMillis();
            if (listener != null && now - lastListened > intervalMs) {
                lastListened = now;
                listener.onProgress(offset, Constant.OP_UPLOAD);
            }

            return res;
        }

    }
}
